package com.company.smmsoperation.processor;

import jodd.http.Cookie;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * 批量删除 sm.ms 图片文件，慎用！
 *
 * @author Song, Wei
 * Date: 2022/3/31 11:36
 */
public class BatchDeletePicture implements PageProcessor {

    private static StringBuilder text = new StringBuilder();

    @Override
    public void process(Page page) {
        for (int i = 1; i <= 30; i++) {
            String s = page.getHtml().xpath("//*[@id=\"table-picture\"]/tbody/tr[" + i + "]/td[1]/label/input/@value").toString();
            text.append(s).append("\n");
        }
    }

    @Override
    public Site getSite() {
        Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000);
        site.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.55");
        // 添加 token 和 cookie 、 Authorization
        site.addHeader("token", "c5c1ef48ecce1eb209a61ab2588de187f044ab11")
                .addHeader("Authorization", "******")
                .addCookie("PHPSESSID", "ik7ucjactpd3g7cen4baq7tft9")
                .addCookie("SMMSrememberme", "27732%3Ac77b0477886927c8e9a84797546dd73828529bc2");
        return site;
    }

    public static void main(String[] args) {
        Cookie cookie1 = new Cookie("PHPSESSID", "ik7ucjactpd3g7cen4baq7tft9");
        Cookie cookie2 = new Cookie("SMMSrememberme", "27732%3Ac77b0477886927c8e9a84797546dd73828529bc2");

        for (int i = 1; i <= 2; i++) {
            Spider.create(new BatchDeletePicture())
                    .addUrl("https://sm.ms/home/picture?page=" + i)
                    .thread(5)
                    .run();
        }
        String[] split = text.toString().split("\n");
        System.out.println(text);
        // 构建删除请求
        HttpRequest request = HttpRequest.post("https://sm.ms/home/picture/delete")
                .header("Authorization", "phQdsoPXaQiPyYhJFIMj0HL12MZmTB34")
                .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.55")
                .query("token", "d790304c2578c6a1e2fd89b6f2cd56aa2a0ef579")
                .cookies(cookie1, cookie2)
                .contentType("multipart/form-data")
                .connectionTimeout(50000);
        for (String s : split) {
            // 批量删除需要上传的图片ID
            request.query("id[]", s);
        }
        HttpResponse response = request.send();
        System.out.println(response);
    }
}
